<template>
  <div>
    <i-dialog
      :title="title"
      :visible="visible"
      width="642px"
      :close-on-click-modal="false"
      @close="outerClose"
    >
      <i-form
        :items="formItems"
        :model="form"
        ref="form"
        :rules="rules"
        label-width="120px"
        class="demo-form"
      >
        <template slot="batchAdd">
          <el-form-item label="导入" prop="batchData">
            <LoadFile v-model="batchData" ref="loadFile" />
          </el-form-item>
        </template>
      </i-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </i-dialog>
  </div>
</template>
<script>
import formValidate from '@/utils/validate'
import LoadFile from '@/components/LoadFile'
export default {
  name: 'PresentTimeCard',
  components: { LoadFile },
  props: {
    isBatch: {
      type: Boolean,
      default: false,
    },
    fromPage: {
      type: String,
    },
    visible: {
      type: Boolean,
      required: true,
    },
    items: {
      type: Array,
      default: () => [
        'mobile',
        'confirmMobile',
        'merchantType',
        'staId',
        'timeCardType',
        'timeCardRule',
        'initialTime',
        'timeCardExpire',
        'batchAdd',
      ],
    },
    cardAttr: {
      type: Object,
      default: () => {},
    },
    api: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      batchData: [],
      form: { timeCardType: 1 },
      allItems: [
        {
          type: 'text',
          value: 'mobile',
          label: '用户手机号',
          required: true,
          // ifRender: () => {
          //   return this.fromPage === 'order/timecard' && !this.isBatch
          // },
        },
        {
          type: 'text',
          value: 'confirmMobile',
          label: '手机号确认',
          required: true,
          // ifRender: () => {
          //   return this.fromPage === 'order/timecard' && !this.isBatch
          // },
        },
        {
          type: 'select',
          value: 'merchantType',
          label: '通用时长卡类型',
          placeholder: '请选择通用时长卡类型',
          clearable: true,
          required: true,
          options: [
            {
              label: '通用时长卡',
              value: 1,
            },
            {
              label: '部分电站通用时长卡',
              value: 2,
            },
          ],
        },
        {
          type: 'select',
          value: 'staId',
          label: '时长卡电站',
          placeholder: '请选择时长卡电站',
          clearable: true,
          required: true,
          prop: {
            label: 'stationName',
            value: 'id',
          },
        },
        {
          type: 'radio',
          value: 'timeCardType',
          label: '时长卡类型',
          clearable: true,
          required: true,
          options: [
            {
              text: '电站时长卡',
              label: 1,
            },
            {
              text: '自定义时长卡',
              label: 2,
            },
          ],
        },
        {
          type: 'select',
          value: 'timeCardRule',
          label: '时长卡',
          placeholder: '请选择时长卡套餐',
          clearable: true,
          required: true,
          change: (val) => {
            if (this.items.includes('merchantType')) {
              let index = val.split(':')[1]
              let item = this.merchant[this.form.merchantType - 1][index]
              this.form.powerCharging = item.powerCharging
              this.form.stationIds = item.stationIds
            }
          },
          ifRender: () => {
            return this.form.timeCardType === 1
          },
        },
        {
          type: 'inputNumber',
          value: 'initialTime',
          label: '时长',
          placeholder: '请输入时长卡时长（小时）',
          min: 1,
          max: 8640,
          ifRender: () => this.form.timeCardType === 2,
        },
        {
          type: 'inputNumber',
          value: 'timeCardExpire',
          label: '有效期',
          min: 1,
          max: 99999,
          placeholder: '请输入时长卡有效期，不填则为无限期（天）',
          ifRender: () => this.form.timeCardType === 2,
        },
        {
          slot: 'batchAdd',
          value: 'batchAdd',
          // ifRender: () => {
          //   return this.isBatch
          // },
        },
      ],
      rules: {
        mobile: [{ validator: formValidate('validateMobile') }],
        confirmMobile: [
          {
            validator: (rules, value, callback) => {
              if (this.form.mobile !== this.form.confirmMobile) {
                callback(new Error('电话号码不一致'))
              } else {
                callback()
              }
            },
          },
          {
            validator: formValidate('validateMobile'),
          },
        ],
        // batchData: [
        //   {
        //     validator: (rules, value, callback) => {
        //       if (!Array.isArray(this.batchData) || this.batchData.length < 1) {
        //         callback(new Error('请上传正确的批量赠送表格'))
        //       } else {
        //         callback()
        //       }
        //     },
        //   },
        // ],
      },
    }
  },
  computed: {
    formItems() {
      return this.allItems.filter((item) => this.items.includes(item.value))
    },
    title() {
      if (this.items.includes('staId')) return '赠送时长卡'
      if (this.items.includes('merchantType')) return '赠送通用时长卡'
      return '赠送时长卡'
    },
  },
  watch: {
    'form.staId': {
      handler(val) {
        for (let item of this.stationList || []) {
          let index = this.allItems.findIndex(
            (item) => item.value === 'timeCardRule'
          )
          if (index < 0) return

          let formItem = this.allItems[index] // timeCardRule
          formItem.options = [] //todo 要修改iform组件
          this.form.timeCardRule = this.form.timeCardRule && ''
          if (item.id === val) {
            if (item.timeCardRule) {
              let timecardArr = item.timeCardRule.split(';')
              timecardArr.forEach((innerItem) => {
                let ruleArr = innerItem.split(',')
                ruleArr.length === 2 ? ruleArr.push('无限') : null
                formItem.options.push({
                  label: `时长${ruleArr[0]}小时，有效期:${ruleArr[2]}天`,
                  value: innerItem,
                })
              })
            }
            this.form.powerCharging = item.timecardPowerCharging
            this.$set(this.allItems, index, formItem)
            break
          }
        }
      },
    },
    'form.merchantType': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          let index = this.allItems.findIndex(
            (item) => item.value === 'timeCardRule'
          )
          if (index < 0) return

          let formItem = this.allItems[index] // timeCardRule
          formItem.options = [] // 要修改iform组件
          this.form.timeCardRule = this.form.timeCardRule && ''
          this.merchant[val - 1].forEach((item, index) => {
            formItem.options.push({
              label: `时长${item.initialTime}小时，有效期:${
                item.periodOfValidity ? item.periodOfValidity : '无限'
              }天`,
              value: item.periodOfValidity
                ? `${item.initialTime},${item.price},${item.periodOfValidity}:${index}`
                : `${item.initialTime},${item.price}:${index}`,
            })
          })
          this.$set(this.allItems, index, formItem)
        }
      },
    },
  },
  created() {
    this.form = {
      timeCardType: 1,
    }
    if (this.items.includes('staId')) return this._handleTimeCards('staId')
    if (this.items.includes('merchantType'))
      return this._handleTimeCards('merchantType')
    if (this.items.includes('timeCardRule'))
      return this._handleTimeCards('timeCardRule')
  },
  methods: {
    _handleTimeCards(type) {
      const handler = {
        staId: this._stationList,
        merchantType: this._merchantTimeCardList,
        timeCardRule: this._timeCardRuleList,
      }
      return handler[type]()
    },
    _stationList() {
      this.api['staId']().then((res) => {
        this.stationList = res

        let index = this.allItems.findIndex((item) => item.value === 'staId')
        if (index < 0) return
        let item = this.allItems[index]
        item.options = res
        this.$set(this.allItems, index, item)
      })
    },
    _merchantTimeCardList() {
      this.api['merchantType']().then(
        (res) => {
          this.timeCardList = res
          this.merchant = [
            this.timeCardList.filter((item) => !item.stationIds),
            this.timeCardList.filter((item) => item.stationIds),
          ]
        },
        () => {
          this.merchant = [[], []]
        }
      )
    },
    _timeCardRuleList() {
      let params = {
        id: this.cardAttr.id,
      }
      this.api['timeCardRule'](params).then((res) => {
        this.timeCardList = res

        let index = this.allItems.findIndex(
          (item) => item.value === 'timeCardRule'
        )
        if (index < 0) return
        let item = this.allItems[index] // staId
        item.options = res.map((item) => {
          return {
            label: `时长${item.initialTime}小时，有效期:${
              item.timeCardExpire ? item.timeCardExpire : '无限'
            }天`,
            value: item.timeCardExpire
              ? `${item.initialTime},${item.price},${item.timeCardExpire}`
              : `${item.initialTime},${item.price}`,
          }
        })
        this.form.staId = this.cardAttr.id
        this.$set(this.allItems, index, item)
      })
    },
    outerOpen() {},
    outerClose() {
      this.form = {
        timeCardType: 1,
      }
      this.$emit('update:visible', false)
    },
    refreshTable() {
      this.$emit('refreshTable')
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {
            mobile: this.cardAttr.mobile,
          }
          params = Object.assign({}, params, this.form)
          if (this.form.timeCardRule) {
            let ruleArr = this.form.timeCardRule.split(':')[0].split(',')
            ruleArr.length === 2 ? ruleArr.push('无限') : null
            params = Object.assign(
              {},
              params,
              { initialTime: parseInt(ruleArr[0]) },
              ruleArr[2] !== '无限' && { timeCardExpire: parseInt(ruleArr[2]) }
            )
          }
          params.merchantType && delete params.merchantType
          params.timeCardRule && delete params.timeCardRule
          params.timeCardType && delete params.timeCardType
          !params.timeCardExpire && delete params.timeCardExpire
          !params.stationIds && delete params.stationIds
          params.confirmMobile && delete this.confirmMobile

          if (this.items.includes('batchAdd')) {
            if (!Array.isArray(this.batchData) || this.batchData.length < 0) {
              this.$message({
                message: '请上传正确的批量赠送表格',
                type: 'warning',
                showClose: true,
              })
              this.$refs.loadFile.onRemove()
              return
            }

            let phoneArr = []
            let phoneStr = ''
            let phoneReg = /^1[0-9]{10}$/
            this.batchData.some((item) => {
              if (item['用户手机号']) {
                let phone = item['用户手机号']
                  .toString()
                  .replace(/(^\s*)|(\s*$)/g, '')
                phoneArr.push(phone)
                if (!phoneReg.test(phone)) {
                  this.$message({
                    showClose: true,
                    message: `${phone}, 格式错误请修正！`,
                    type: 'warning',
                  })
                  phoneArr = []
                  return true
                }
              }
            })
            if (phoneArr.length > 0) {
              phoneStr = phoneArr.join(',')
            } else {
              this.$message({
                message: '数据导入失败',
                type: 'error',
                offset: 60,
              })
              this.$refs.loadFile.onRemove()
              return
            }

            params.mobile = phoneStr
          }
          this.api['submit']({ ...params }).then(
            () => {
              this.$message({
                message: '赠送成功',
                type: 'success',
              })
              this.outerClose()
              this.refreshTable()
            },
            () => {
              this.outerClose()
              this.refreshTable()
            }
          )
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.timecard-item {
  width: 50%;
  display: inline-block;
  .el-input {
    width: 80%;
  }
}
</style>
